import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import '../controllers/device_data_controller.dart';

class DeviceDataTableView extends GetView<DeviceDataController> {
  const DeviceDataTableView({Key? key}) : super(key: key);

  // 重写get controller，确保使用正确的标签获取控制器
  @override
  DeviceDataController get controller {
    final args = Get.arguments as Map<String, dynamic>?;
    final deviceId = args?['deviceId'] as int? ?? 0;
    final deviceName = args?['deviceName'] as String? ?? '';
    
    try {
      // 尝试查找已存在的控制器
      return Get.find<DeviceDataController>(tag: 'device_data_$deviceId');
    } catch (e) {
      // 如果找不到，创建一个新的控制器实例
      print('无法找到标签为device_data_$deviceId的控制器，创建新实例');
      final controller = DeviceDataController(
        deviceId: deviceId,
        deviceName: deviceName,
      );
      Get.put<DeviceDataController>(
        controller,
        permanent: true,
        tag: 'device_data_$deviceId',
      );
      return controller;
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final dateFormat = DateFormat('yyyy-MM-dd HH:mm:ss');

    return Scaffold(
      appBar: AppBar(
        title: Text(controller.deviceName.isEmpty ? '设备数据表格' : '${controller.deviceName}数据表格'),
        centerTitle: true,
        actions: [
          Obx(() => controller.isRefreshing.value 
            ? Container(
                width: 40,
                alignment: Alignment.center,
                child: const SizedBox(
                  width: 20,
                  height: 20,
                  child: CircularProgressIndicator(strokeWidth: 2),
                ),
              )
            : IconButton(
                icon: const Icon(Icons.refresh),
                onPressed: () => controller.refreshData(),
              ),
          ),
        ],
      ),
      body: SafeArea(
        child: Column(
          children: [
            // 时间范围过滤面板 - 始终显示
            _buildFilterPanel(theme),
            
            // 内容区域
            Expanded(
              child: Obx(() {
                // 初始加载时显示加载中
                if (controller.isLoading.value && controller.currentTimestamps.isEmpty) {
                  return const Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        SizedBox(
                          width: 40,
                          height: 40,
                          child: CircularProgressIndicator(strokeWidth: 3),
                        ),
                        SizedBox(height: 16),
                        Text('加载设备数据中...',
                          style: TextStyle(fontSize: 16),
                          textAlign: TextAlign.center,
                        ),
                      ],
                    ),
                  );
                }

                // 显示错误信息
                if (controller.errorMessage.value != null && controller.currentTimestamps.isEmpty) {
                  return _buildErrorView(theme);
                }

                // 完全没有数据时显示空状态
                if (controller.totalTimestamps.value == 0 && !controller.isLoading.value) {
                  return _buildEmptyView(theme);
                }

                // 正常显示表格
                return Column(
                  children: [
                    Expanded(
                      child: _buildDataTable(theme, dateFormat, context),
                    ),
                    _buildPaginationControls(theme),
                  ],
                );
              }),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildErrorView(ThemeData theme) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.error_outline, size: 64, color: theme.colorScheme.error),
          const SizedBox(height: 16),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 32.0),
            child: Text(
              controller.errorMessage.value ?? '加载数据时发生错误',
              style: TextStyle(color: theme.colorScheme.error, fontSize: 16),
              textAlign: TextAlign.center,
            ),
          ),
          const SizedBox(height: 24),
          ElevatedButton.icon(
            onPressed: () => controller.refreshData(),
            icon: const Icon(Icons.refresh),
            label: const Text('重试'),
          ),
        ],
      ),
    );
  }

  Widget _buildEmptyView(ThemeData theme) {
    // 根据时间范围显示不同的提示信息
    String mainMessage = '暂无历史数据';
    String subMessage = '设备尚未上报任何数据';
    
    switch(controller.timeRange.value) {
      case '24h':
        subMessage = '设备在过去24小时内没有上报数据';
        break;
      case '7d':
        subMessage = '设备在过去7天内没有上报数据';
        break;
      case '30d':
        subMessage = '设备在过去30天内没有上报数据';
        break;
      case 'latest':
      default:
        // 使用默认消息
        break;
    }
    
    final Color iconColor = theme.brightness == Brightness.dark
        ? Colors.grey.shade500 // 暗色主题图标颜色
        : theme.disabledColor; // 亮色主题图标颜色
    
    final Color textColor = theme.brightness == Brightness.dark
        ? Colors.grey.shade400 // 暗色主题文本颜色
        : theme.disabledColor; // 亮色主题文本颜色
    
    final Color subTextColor = theme.brightness == Brightness.dark
        ? Colors.grey.shade500 // 暗色主题次要文本颜色
        : Colors.grey;        // 亮色主题次要文本颜色
    
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.table_chart_outlined, size: 64, color: iconColor),
          const SizedBox(height: 16),
          Text(mainMessage, style: TextStyle(color: textColor, fontSize: 16)),
          const SizedBox(height: 8),
          Text(subMessage, style: TextStyle(color: textColor, fontSize: 14)),
          const SizedBox(height: 12),
          Text('请尝试选择其他时间范围', style: TextStyle(color: subTextColor, fontSize: 13)),
          const SizedBox(height: 24),
          ElevatedButton.icon(
            onPressed: () => controller.refreshData(),
            icon: const Icon(Icons.refresh),
            label: const Text('刷新'),
            style: ElevatedButton.styleFrom(
              backgroundColor: theme.brightness == Brightness.dark
                  ? theme.primaryColor // 暗色主题按钮颜色
                  : null,              // 亮色主题使用默认颜色
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildFilterPanel(ThemeData theme) {
    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      elevation: 1,
      color: theme.brightness == Brightness.dark 
          ? Colors.grey.shade800  // 暗色主题卡片背景
          : null,               // 亮色主题使用默认颜色
      child: Padding(
        padding: const EdgeInsets.all(12.0),
        child: Row(
          children: [
            Text('时间范围:', 
              style: TextStyle(
                fontWeight: FontWeight.bold,
                color: theme.brightness == Brightness.dark
                    ? Colors.grey.shade200 // 暗色主题文本颜色
                    : null,               // 亮色主题使用默认颜色
              ),
            ),
            const SizedBox(width: 16),
            Expanded(
              child: SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: Row(
                  children: [
                    _buildTimeRangeChip('latest', '最新数据', theme),
                    const SizedBox(width: 8),
                    _buildTimeRangeChip('24h', '24小时', theme),
                    const SizedBox(width: 8),
                    _buildTimeRangeChip('7d', '7天', theme),
                    const SizedBox(width: 8),
                    _buildTimeRangeChip('30d', '30天', theme),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildTimeRangeChip(String value, String label, ThemeData theme) {
    return Obx(() => ChoiceChip(
          label: Text(label),
          selected: controller.timeRange.value == value,
          onSelected: (_) => controller.changeTimeRange(value),
          selectedColor: theme.brightness == Brightness.dark
              ? theme.primaryColor.withOpacity(0.4)  // 暗色主题选中颜色
              : theme.primaryColor.withOpacity(0.2), // 亮色主题选中颜色
          backgroundColor: theme.brightness == Brightness.dark
              ? Colors.grey.shade700  // 暗色主题背景色
              : null,               // 亮色主题使用默认颜色
          labelStyle: TextStyle(
            fontSize: 12,
            color: controller.timeRange.value == value 
                ? (theme.brightness == Brightness.dark 
                    ? Colors.white  // 暗色主题下选中文本颜色
                    : theme.primaryColor) // 亮色主题下选中文本颜色
                : (theme.brightness == Brightness.dark 
                    ? Colors.grey.shade300 // 暗色主题下未选中文本颜色
                    : theme.textTheme.bodySmall?.color), // 亮色主题下未选中文本颜色
          ),
          padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
        ));
  }

  Widget _buildDataTable(ThemeData theme, DateFormat dateFormat, BuildContext context) {
    return Obx(() {
      // 显示加载动画
      if (controller.isLoading.value && controller.paginatedTimestamps.isEmpty) {
        return const Center(child: Padding(
          padding: EdgeInsets.all(16.0),
          child: CircularProgressIndicator(),
        ));
      }
      
      // 获取所有属性而不仅仅是可见的数据系列
      // 直接从controller.properties获取所有可以图表化的属性
      final allProperties = controller.properties.toList();
      
      // 没有选中任何属性时的提示
      if (allProperties.isEmpty) {
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.visibility_off, size: 32, color: theme.disabledColor),
              const SizedBox(height: 12),
              Text('未找到可显示的属性',
                style: TextStyle(color: theme.disabledColor),
              ),
            ],
          ),
        );
      }
      
      // 当前页没有数据时的提示
      if (controller.paginatedTimestamps.isEmpty && !controller.isLoading.value) {
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.table_rows_outlined, size: 32, color: theme.disabledColor),
              const SizedBox(height: 12),
              const Text('当前页面无数据',
                style: TextStyle(color: Colors.grey),
              ),
            ],
          ),
        );
      }
      
      // 构建表格列 - 使用所有属性
      final columns = <DataColumn>[
        DataColumn(
          label: Text('时间', style: TextStyle(
            fontWeight: FontWeight.bold,
            color: theme.brightness == Brightness.dark
                ? Colors.grey.shade200 // 暗色主题下标题颜色
                : null,               // 亮色主题使用默认颜色
          )),
          tooltip: '数据记录时间',
        ),
        // 为每个属性创建一列，不仅仅是可见系列
        ...allProperties.where((prop) => prop.isReadable).map((prop) {
          final displayName = '${prop.name}${prop.unit != null ? "(${prop.unit})" : ""}';
          return DataColumn(
            label: Text(
              _getFormattedPropertyName(displayName),
              style: TextStyle(
                fontWeight: FontWeight.bold,
                // 使用固定的高对比度颜色方案
                color: _getFixedHeaderColor(displayName, theme.brightness == Brightness.dark),
                fontSize: 14,
              ),
              overflow: TextOverflow.ellipsis,
            ),
            tooltip: displayName,
          );
        }),
      ];

      // 构建表格行 - 每页显示tablePageSize条数据
      final rows = controller.paginatedTimestamps.map((timestamp) {
        return DataRow(
          cells: [
            // 时间列
            DataCell(
              Text(
                dateFormat.format(timestamp),
                style: const TextStyle(fontSize: 12),
              ),
            ),
            // 为每个属性创建单元格
            ...allProperties.where((prop) => prop.isReadable).map((prop) {
              // 查找该时间戳对应的数据点
              final dataPoint = _findDataPointForProperty(prop, timestamp);
              
              return DataCell(
                Text(
                  // 如果有数据则格式化显示，否则显示'-'
                  dataPoint != null ? 
                    _formatPropertyValue(dataPoint, prop.dataType) : 
                    '-',
                  style: TextStyle(
                    color: dataPoint != null 
                        ? (theme.brightness == Brightness.dark 
                            ? _getPropertyColor(prop.name, true)  // 暗色主题
                            : _getPropertyColor(prop.name, false)) // 亮色主题
                        : (theme.brightness == Brightness.dark 
                            ? Colors.grey.shade500  // 暗色主题下空值颜色
                            : Colors.grey),        // 亮色主题下空值颜色
                    fontWeight: dataPoint != null ? FontWeight.w500 : null,
                    fontSize: 12,
                  ),
                  textAlign: TextAlign.center,
                ),
              );
            }),
          ],
        );
      }).toList();
      
      // 使用SingleChildScrollView实现水平滚动
      return Stack(
        children: [
          RefreshIndicator(
            onRefresh: controller.refreshData,
            child: Padding(
              padding: const EdgeInsets.only(bottom: 2.0),
              child: SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: SizedBox(
                  // 设置最小宽度确保可以滚动刷新
                  width: max(MediaQuery.of(context).size.width, (allProperties.length + 1) * 120.0),
                  child: SingleChildScrollView(
                    physics: const AlwaysScrollableScrollPhysics(),
                    child: DataTable(
                      columns: columns,
                      rows: rows,
                      columnSpacing: 20.0,
                      headingRowHeight: 40.0,
                      dataRowMinHeight: 36.0,
                      dataRowMaxHeight: 40.0,
                      border: TableBorder.all(
                        color: theme.brightness == Brightness.dark 
                            ? Colors.grey.shade700  // 暗色主题边框颜色
                            : Colors.grey.shade300, // 亮色主题边框颜色
                        width: 0.5,
                      ),
                      headingRowColor: MaterialStateProperty.resolveWith<Color>(
                        (states) => theme.brightness == Brightness.dark
                            ? Colors.grey.shade800  // 暗色主题表头背景
                            : Colors.grey.shade100, // 亮色主题表头背景
                      ),
                      dataRowColor: MaterialStateProperty.resolveWith<Color>(
                        (states) => theme.brightness == Brightness.dark
                            ? Colors.grey.shade900.withOpacity(0.7) // 暗色主题行背景
                            : Colors.transparent, // 亮色主题行背景
                      ),
                      dataTextStyle: TextStyle(
                        fontSize: 12,
                        color: theme.brightness == Brightness.dark
                            ? Colors.grey.shade300 // 暗色主题文本颜色
                            : theme.textTheme.bodyMedium?.color, // 亮色主题文本颜色
                      ),
                      // 使用其他方式调整列宽
                      horizontalMargin: 10.0,
                    ),
                  ),
                ),
              ),
            ),
          ),
          // 如果正在刷新，显示一个小的刷新指示器
          if (controller.isRefreshing.value && !controller.isLoading.value)
            Positioned(
              top: 10,
              right: 10,
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.black.withOpacity(0.5),
                  borderRadius: BorderRadius.circular(20),
                ),
                padding: const EdgeInsets.all(8),
                child: const SizedBox(
                  width: 20,
                  height: 20,
                  child: CircularProgressIndicator(
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                    strokeWidth: 2,
                  ),
                ),
              ),
            ),
        ],
      );
    });
  }

  Widget _buildPaginationControls(ThemeData theme) {
    return Obx(() => Container(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
          decoration: BoxDecoration(
            color: theme.brightness == Brightness.dark
                ? Colors.grey.shade900  // 暗色主题背景色
                : theme.cardColor,     // 亮色主题使用默认卡片颜色
            border: Border(top: BorderSide(
              color: theme.brightness == Brightness.dark
                  ? Colors.grey.shade700  // 暗色主题边框颜色
                  : Colors.grey.shade200, // 亮色主题边框颜色
              width: 1,
            )),
            boxShadow: [
              BoxShadow(
                color: theme.brightness == Brightness.dark
                    ? Colors.black.withOpacity(0.2)  // 暗色主题阴影
                    : Colors.black.withOpacity(0.05), // 亮色主题阴影
                blurRadius: 1,
                offset: const Offset(0, -1),
              ),
            ],
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  Text(
                    '总计: ${controller.totalTimestamps.value} 条 ',
                    style: theme.textTheme.bodySmall,
                  ),
                  SizedBox(width: 8),
                  // 当显示全部数据时显示总条数
                  Obx(() {
                    return controller.showAllData.value 
                      ? Text(
                          '(显示: ${controller.paginatedTimestamps.length}/${controller.totalTimestamps.value})',
                          style: TextStyle(
                            fontSize: 12,
                            color: theme.primaryColor,
                            fontWeight: FontWeight.bold,
                          ),
                        )
                      : SizedBox.shrink();
                  }),
                  SizedBox(width: 8),
                  // 显示全部数据开关
                  Row(
                    children: [
                      Text(
                        '显示全部: ',
                        style: theme.textTheme.bodySmall,
                      ),
                      Switch(
                        value: controller.showAllData.value,
                        onChanged: (val) => controller.toggleShowAllData(),
                        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        activeColor: theme.primaryColor,
                      ),
                    ],
                  ),
                ],
              ),
              // 只有在非全部显示模式下才显示分页控制
              Obx(() => controller.showAllData.value
                ? const SizedBox() // 全部显示模式下不显示分页控制
                : Row(
                    children: [
                      IconButton(
                        icon: const Icon(Icons.chevron_left),
                        iconSize: 20,
                        tooltip: '上一页',
                        onPressed: controller.tableCurrentPage.value > 1 ? controller.previousTablePage : null,
                        visualDensity: VisualDensity.compact,
                      ),
                      Container(
                        constraints: const BoxConstraints(minWidth: 80),
                        alignment: Alignment.center,
                        child: Text(
                          '第 ${controller.tableCurrentPage.value} / ${controller.totalTablePages} 页',
                          style: theme.textTheme.bodySmall?.copyWith(fontWeight: FontWeight.bold),
                        ),
                      ),
                      IconButton(
                        icon: const Icon(Icons.chevron_right),
                        iconSize: 20,
                        tooltip: '下一页',
                        onPressed: controller.tableCurrentPage.value < controller.totalTablePages ? controller.nextTablePage : null,
                        visualDensity: VisualDensity.compact,
                      ),
                    ],
                  ),
              ),
            ],
          ),
        ));
  }
  
  // 计算最大值，避免导入dart:math
  double max(double a, double b) => a > b ? a : b;

  // 为每种属性提供固定的高对比度颜色
  Color _getFixedHeaderColor(String propertyName, bool isDarkTheme) {
    // 标准化属性名称进行比较
    String normalizedName = propertyName.toLowerCase().trim();
    
    // 为常见属性分配固定颜色 - 添加波浪相关参数的颜色
    if (normalizedName.contains('温度') || normalizedName.contains('气温') || normalizedName.contains('水温')) {
      return isDarkTheme ? Colors.lightBlue.shade300 : Colors.blue.shade700;
    } else if (normalizedName.contains('湿度')) {
      return isDarkTheme ? Colors.teal.shade300 : Colors.teal.shade700;
    } else if (normalizedName.contains('压') || normalizedName.contains('气压')) {
      return isDarkTheme ? Colors.purple.shade300 : Colors.purple.shade700;
    } else if (normalizedName.contains('浊度')) {
      return isDarkTheme ? Colors.orange.shade300 : Colors.orange.shade700;
    } else if (normalizedName.contains('盐度')) {
      return isDarkTheme ? Colors.cyan.shade300 : Colors.cyan.shade700;
    } else if (normalizedName.contains('风') || normalizedName.contains('速度')) {
      return isDarkTheme ? Colors.indigo.shade300 : Colors.indigo.shade700;
    } else if (normalizedName.contains('雨') || normalizedName.contains('降水')) {
      return isDarkTheme ? Colors.blueGrey.shade300 : Colors.blueGrey.shade700;
    } else if (normalizedName.contains('辐射') || normalizedName.contains('光')) {
      return isDarkTheme ? Colors.amber.shade300 : Colors.amber.shade700;
    } else if (normalizedName.contains('电') || normalizedName.contains('压')) {
      return isDarkTheme ? Colors.red.shade300 : Colors.red.shade800;
    } else if (normalizedName.contains('质量') || normalizedName.contains('pm')) {
      return isDarkTheme ? Colors.green.shade300 : Colors.green.shade700;
    } else if (normalizedName.contains('波高') || normalizedName.contains('hmax') || normalizedName.contains('h3') || normalizedName.contains('h10') || normalizedName.contains('ha')) {
      return isDarkTheme ? Colors.deepPurple.shade300 : Colors.deepPurple.shade700;
    } else if (normalizedName.contains('波周期') || normalizedName.contains('tmax') || normalizedName.contains('t3') || normalizedName.contains('t10') || normalizedName.contains('ta')) {
      return isDarkTheme ? Colors.blue.shade300 : Colors.blue.shade700;
    } else if (normalizedName.contains('跨零点') || normalizedName.contains('cropoints')) {
      return isDarkTheme ? Colors.amber.shade300 : Colors.amber.shade700;
    } else if (normalizedName.contains('波向') || normalizedName.contains('方向谱') || normalizedName.contains('dmean') || normalizedName.contains('dp')) {
      return isDarkTheme ? Colors.teal.shade300 : Colors.teal.shade700;
    } else if (normalizedName.contains('频率') || normalizedName.contains('fp')) {
      return isDarkTheme ? Colors.lime.shade300 : Colors.lime.shade700;
    } else if (normalizedName.contains('有效波高') || normalizedName.contains('hm0')) {
      return isDarkTheme ? Colors.deepOrange.shade300 : Colors.deepOrange.shade700;
    } else if (normalizedName.contains('功率谱') || normalizedName.contains('tp')) {
      return isDarkTheme ? Colors.indigo.shade300 : Colors.indigo.shade700;
    } else if (normalizedName.contains('深度') || normalizedName.contains('depth')) {
      return isDarkTheme ? Colors.lightBlue.shade300 : Colors.lightBlue.shade700;
    } else if (normalizedName.contains('经度') || normalizedName.contains('longitude')) {
      return isDarkTheme ? Colors.pink.shade300 : Colors.pink.shade700;
    } else if (normalizedName.contains('维度') || normalizedName.contains('latitude')) {
      return isDarkTheme ? Colors.purple.shade300 : Colors.purple.shade700;
    } else if (normalizedName.contains('接收卡号') || normalizedName.contains('fromcard')) {
      return isDarkTheme ? Colors.brown.shade300 : Colors.brown.shade700;
    } else if (normalizedName.contains('发送卡号') || normalizedName.contains('tocard')) {
      return isDarkTheme ? Colors.grey.shade400 : Colors.grey.shade700;
    }
    
    // 对于其他未知属性，使用安全的默认颜色
    return isDarkTheme ? Colors.white : Colors.black87;
  }

  // 为属性名称添加单位
  String _getFormattedPropertyName(String propertyName) {
    // 标准化属性名称进行比较
    String normalizedName = propertyName.toLowerCase().trim();
    
    // 匹配常见属性名并添加单位
    if (normalizedName.contains('温度') || normalizedName.contains('气温') || normalizedName.contains('水温')) {
      // 如果属性名中已经包含了单位，则不添加
      return propertyName.contains('℃') ? propertyName : '$propertyName(℃)';
    } else if (normalizedName.contains('湿度')) {
      return propertyName.contains('%') ? propertyName : '$propertyName(%)';
    } else if (normalizedName.contains('压') || normalizedName.contains('气压')) {
      return propertyName.contains('hPa') ? propertyName : '$propertyName(hPa)';
    } else if (normalizedName.contains('浊度')) {
      return propertyName.contains('NTU') ? propertyName : '$propertyName(NTU)';
    } else if (normalizedName.contains('盐度')) {
      return propertyName.contains('ppt') ? propertyName : '$propertyName(ppt)';
    } else if (normalizedName.contains('风速')) {
      return propertyName.contains('m/s') ? propertyName : '$propertyName(m/s)';
    } else if (normalizedName.contains('风向')) {
      return propertyName.contains('°') ? propertyName : '$propertyName(°)';
    } else if (normalizedName.contains('雨量') || normalizedName.contains('降水')) {
      return propertyName.contains('mm') ? propertyName : '$propertyName(mm)';
    } else if (normalizedName.contains('辐射') || normalizedName.contains('光照')) {
      return propertyName.contains('lux') ? propertyName : '$propertyName(lux)';
    } else if (normalizedName.contains('电压')) {
      return propertyName.contains('V') ? propertyName : '$propertyName(V)';
    } else if (normalizedName.contains('电流')) {
      return propertyName.contains('A') ? propertyName : '$propertyName(A)';
    } else if (normalizedName.contains('pm2.5')) {
      return propertyName.contains('μg/m³') ? propertyName : '$propertyName(μg/m³)';
    } else if (normalizedName.contains('波高') || normalizedName.contains('hmax') || normalizedName.contains('h3') || normalizedName.contains('h10') || normalizedName.contains('ha') || normalizedName.contains('hm0')) {
      return propertyName.contains('m') ? propertyName : '$propertyName(m)';
    } else if (normalizedName.contains('波周期') || normalizedName.contains('tmax') || normalizedName.contains('t3') || normalizedName.contains('t10') || normalizedName.contains('ta') || normalizedName.contains('tp')) {
      return propertyName.contains('s') ? propertyName : '$propertyName(s)';
    } else if (normalizedName.contains('跨零点') || normalizedName.contains('cropoints')) {
      return propertyName.contains('个') ? propertyName : '$propertyName(个)';
    } else if (normalizedName.contains('波向') || normalizedName.contains('方向谱') || normalizedName.contains('dmean') || normalizedName.contains('dp')) {
      return propertyName.contains('°') ? propertyName : '$propertyName(°)';
    } else if (normalizedName.contains('频率') || normalizedName.contains('fp')) {
      return propertyName.contains('Hz') ? propertyName : '$propertyName(Hz)';
    } else if (normalizedName.contains('深度') || normalizedName.contains('depth')) {
      return propertyName.contains('m') ? propertyName : '$propertyName(m)';
    }
    
    // 如果没有匹配的单位，返回原始名称
    return propertyName;
  }

  // 修改查找属性数据点的辅助方法，更好地处理属性匹配
  dynamic _findDataPointForProperty(PropertyDefinition prop, DateTime timestamp) {
    // 特别处理几个特殊的属性 - 修复设备名称和传输时间等常见问题字段
    // 这些字段因为大小写或标识符不同导致无法匹配
    final specialProps = {
      'transmitTime': ['transmitTime', 'transmit_time', 'TransmitTime', '传输时间'],
      'transmittime': ['transmitTime', 'transmit_time', 'TransmitTime', '传输时间'],
      '传输时间': ['transmitTime', 'transmit_time', 'TransmitTime', '传输时间'],
      'fname': ['fname', 'Fname', 'deviceName', 'device_name', '设备名称', 'DeviceName', 'name'],
      '设备名称': ['fname', 'Fname', 'deviceName', 'device_name', '设备名称', 'DeviceName', 'name'],
      'devicename': ['fname', 'Fname', 'deviceName', 'device_name', '设备名称', 'DeviceName', 'name'],
      'tocard': ['toCard', 'to_card', 'ToCard', '发送卡号'],
      'toCard': ['toCard', 'to_card', 'ToCard', '发送卡号'],
      '发送卡号': ['toCard', 'to_card', 'ToCard', '发送卡号'],
      'fromcard': ['fromCard', 'from_card', 'FromCard', '接收卡号'],
      'fromCard': ['fromCard', 'from_card', 'FromCard', '接收卡号'],
      '接收卡号': ['fromCard', 'from_card', 'FromCard', '接收卡号'],
    };
    
    // 处理特殊属性的情况
    final propIdLower = prop.identifier.toLowerCase();
    final propNameLower = prop.name.toLowerCase();
    
    // 检查是否是特殊属性，先直接从原始数据中尝试获取值
    List<String>? specialPropKeys = null;
    
    if (specialProps.containsKey(prop.identifier)) {
      specialPropKeys = specialProps[prop.identifier];
    } else if (specialProps.containsKey(propIdLower)) {
      specialPropKeys = specialProps[propIdLower];
    } else if (specialProps.containsKey(prop.name)) {
      specialPropKeys = specialProps[prop.name];
    } else if (specialProps.containsKey(propNameLower)) {
      specialPropKeys = specialProps[propNameLower];
    }
    
    // 如果找到特殊属性映射，尝试所有可能的键名
    if (specialPropKeys != null) {
      for (final key in specialPropKeys) {
        final value = controller.getPropertyValueForTimestamp(key, timestamp);
        if (value != null) {
          return value;
        }
      }
    }
    
    // 1. 首先尝试从controller的getPropertyValueForTimestamp方法获取数据
    final propValue = controller.getPropertyValueForTimestamp(prop.identifier, timestamp);
    if (propValue != null) {
      return propValue;
    }
    
    // 2. 如果上面的方法没有找到值，继续使用标准方法查找
    final propIdentifier = prop.identifier.toLowerCase();
    final propName = prop.name.toLowerCase();
    
    // 创建可能的匹配关键字列表
    List<String> possibleMatches = [propIdentifier, propName];
    
    // 添加常见的波浪参数别名
    if (propIdentifier.contains('hmax') || propName.contains('最大波高')) {
      possibleMatches.addAll(['hmax', 'hmax_t', 'h_max', '最大波高']);
    } else if (propIdentifier.contains('tmax') || propName.contains('最大波周期')) {
      possibleMatches.addAll(['tmax', 'tmax_t', 't_max', '最大波周期']);
    } else if (propIdentifier.contains('h3') || propName.contains('1/3大波高')) {
      possibleMatches.addAll(['h3', 'h3_t', 'h_3', 'h1/3', '1/3波高']);
    } else if (propIdentifier.contains('t3') || propName.contains('1/3大波周期')) {
      possibleMatches.addAll(['t3', 't3_t', 't_3', 't1/3', '1/3波周期']);
    } else if (propIdentifier.contains('h10') || propName.contains('1/10大波高')) {
      possibleMatches.addAll(['h10', 'h10_t', 'h_10', 'h1/10', '1/10波高']);
    } else if (propIdentifier.contains('t10') || propName.contains('1/10大波周期')) {
      possibleMatches.addAll(['t10', 't10_t', 't_10', 't1/10', '1/10波周期']);
    } else if (propIdentifier.contains('ha') || propName.contains('平均波高')) {
      possibleMatches.addAll(['ha', 'ha_t', 'h_a', 'havg', '平均波高']);
    } else if (propIdentifier.contains('ta') || propName.contains('平均波周期')) {
      possibleMatches.addAll(['ta', 'ta_t', 't_a', 'tavg', '平均波周期']);
    } else if (propIdentifier.contains('cropoints') || propName.contains('跨零点')) {
      possibleMatches.addAll(['cropoints', 'zeropoints', 'cro_points', '跨零点个数', '跨零点', 'CroPoints']);
    } else if (propIdentifier.contains('dmean') || propName.contains('平均波向')) {
      possibleMatches.addAll(['dmean', 'd_mean', 'dir_mean', '平均波向', 'Dmean']);
    } else if (propIdentifier.contains('dp') || propName.contains('主波向')) {
      possibleMatches.addAll(['dp', 'd_p', 'dir_p', '主波向', '方向谱', 'Dp']);
    } else if (propIdentifier.contains('fp') || propName.contains('峰值频率')) {
      possibleMatches.addAll(['fp', 'f_p', 'freq_p', '峰值频率', 'Fp']);
    } else if (propIdentifier.contains('hm0') || propName.contains('有效波高')) {
      possibleMatches.addAll(['hm0', 'h_m0', 'h0', '有效波高', 'Hm0']);
    } else if (propIdentifier.contains('tp') || propName.contains('峰值周期')) {
      possibleMatches.addAll(['tp', 't_p', 'period_p', '峰值周期', 'Tp']);
    } else if (propIdentifier.contains('depth') || propName.contains('水深')) {
      possibleMatches.addAll(['depth', 'water_depth', '水深']);
    } else if (propIdentifier.contains('温度') || propName.contains('温度')) {
      possibleMatches.addAll(['temp', 'temperature', 'w_temp', 'water_temp', '温度', '水温', 'W_temp', 'Temperature']);
    } else if (propIdentifier.contains('电压') || propName.contains('电压')) {
      possibleMatches.addAll(['voltage', 'v', 'bt_v', 'battery', '电压', '电池电压', 'Bt_V']);
    } else if (propIdentifier.contains('fromcard') || propName.contains('发送卡号')) {
      possibleMatches.addAll(['fromcard', 'from_card', 'sender', 'send_card', 'tocard', 'to_card', '发送卡号', '接收卡号', 'fromCard', 'toCard']);
    }
    
    // 从chartData中查找数据
    for (var series in controller.combinedChartData) {
      // 先尝试精确匹配（忽略大小写）
      final seriesNameLower = series.name.toLowerCase();
      bool isMatchFound = false;
      
      // 尝试可能的匹配列表
      for (String match in possibleMatches) {
        if (seriesNameLower == match || 
            seriesNameLower.contains(match) || 
            match.contains(seriesNameLower)) {
          final point = series.data.firstWhereOrNull((p) => p.timestamp == timestamp);
          if (point != null) {
            return point.value;
          }
          isMatchFound = true;
          break;
        }
      }
      
      // 如果没有找到匹配，尝试常规的部分匹配
      if (!isMatchFound) {
        if (series.name.toLowerCase().contains(propIdentifier) || 
            propIdentifier.contains(series.name.toLowerCase()) ||
            series.name.toLowerCase().contains(propName) || 
            propName.contains(series.name.toLowerCase())) {
          final point = series.data.firstWhereOrNull((p) => p.timestamp == timestamp);
          if (point != null) {
            return point.value;
          }
        }
      }
    }
    
    // 最后尝试一次直接从所有历史数据中查找（忽略属性名，只匹配时间戳）
    try {
      // 注意：historyDataCache是私有变量，不能直接访问，使用绕过方式
      final cacheKey = '${controller.deviceSn.value}_${controller.timeRange.value}';
      
      // 获取历史数据，使用反射或合法方式访问
      controller.analyzeHistoryDataStructure(); // 这会打印历史数据的结构，不是最优解但可以帮助调试
      
      // 尝试使用属性相关的其他方法
      for (var series in controller.combinedChartData) {
        for (var point in series.data) {
          if ((point.timestamp.difference(timestamp).inSeconds).abs() <= 1) {
            // 如果找到相同时间戳的记录，再次尝试匹配属性
            for (var s in controller.combinedChartData) {
              if (possibleMatches.any((m) => s.name.toLowerCase().contains(m.toLowerCase()) || 
                  m.toLowerCase().contains(s.name.toLowerCase()))) {
                final matchPoint = s.data.firstWhereOrNull((p) => 
                    (p.timestamp.difference(timestamp).inSeconds).abs() <= 1);
                if (matchPoint != null) {
                  return matchPoint.value;
                }
              }
            }
          }
        }
      }
    } catch (e) {
      print('直接查找历史数据时出错: $e');
    }
    
    return null;
  }
  
  // 改进格式化属性值的辅助方法，更好地处理各种数据类型
  String _formatPropertyValue(dynamic value, String dataType) {
    if (value == null) return '-';
    
    try {
      switch (dataType.toLowerCase()) {
        case 'int':
          if (value is num) {
            return value.toInt().toString();
          }
          if (value is String && value.isNotEmpty) {
            try {
              return int.parse(value).toString();
            } catch (_) {}
          }
          break;
          
        case 'float':
        case 'double':
          if (value is num) {
            return value.toStringAsFixed(2);
          }
          if (value is String && value.isNotEmpty) {
            try {
              return double.parse(value).toStringAsFixed(2);
            } catch (_) {}
          }
          break;
          
        case 'boolean':
        case 'bool':
          if (value is bool) {
            return value ? '是' : '否';
          }
          if (value is num) {
            return value != 0 ? '是' : '否';
          }
          if (value is String) {
            if (value.toLowerCase() == 'true' || value == '1') return '是';
            if (value.toLowerCase() == 'false' || value == '0') return '否';
          }
          break;
          
        case 'string':
        case 'text':
          return value.toString();
          
        case 'enum':
          // 枚举值通常直接显示其字符串表示
          return value.toString();
          
        case 'timestamp':
        case 'date':
        case 'time':
          // 尝试将值解析为日期
          if (value is String) {
            try {
              final date = DateTime.parse(value);
              return DateFormat('yyyy-MM-dd HH:mm:ss').format(date);
            } catch (_) {}
          }
          break;
          
        case 'json':
        case 'object':
          // JSON对象尝试以缩略形式显示
          if (value is Map || value is List) {
            return '${value.runtimeType}(...)';
          }
          break;
      }
      
      // 对于未识别的类型或解析失败的情况，返回原始字符串表示
      return value.toString();
    } catch (e) {
      print('格式化属性值失败: $e');
      return value.toString();
    }
  }
  
  // 为属性获取颜色
  Color _getPropertyColor(String propName, bool isDarkTheme) {
    // 重用现有的_getFixedHeaderColor方法获取颜色
    return _getFixedHeaderColor(propName, isDarkTheme);
  }
} 